/* 
 * Copyright (c), nFractals Ltd. All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.parade.distributed;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

import org.parade.Constant;
import org.parade.Parade;
import org.parade.driver.Driver;


/**
 * Distributed lock
 * 
 * 
 * 
 * @author		Lee moon soo
 * 
 * @version		%I%, %G%
 * 
 * @since		1.0
 * 
 */
public class Lock implements java.util.concurrent.locks.Lock, Object{

	private Driver driver;
	private Id id;
	private java.util.concurrent.locks.Lock lock;
	private Condition condition;


	/**
	 * Create Lock using driver provided by singleton Parade object
	 * 
	 * @param id		Cluster wide unique object id
	 */
	public Lock(Id id){
		this.driver = Parade.getDriver();
		this.id = id;
		this.lock = driver.getLock(id);
	}
	
	/**
	 * Create lock using given driver
	 * 
	 * @param driver	Distributed driver to use
	 * @param id		Cluster wide unique object id
	 */
	public Lock(Driver driver, Id id){
		this.driver = driver;
		this.id = id;
		this.lock = driver.getLock(id);
	}

	@Override
	public synchronized Condition newCondition(){
		if(this.condition == null){
			this.condition = new org.parade.distributed.Condition(driver, this);
		} 
		return this.condition;
	}
	
	@Override
	public void lockInterruptibly() throws InterruptedException{
		throw new UnsupportedOperationException("lockInterruptibly is not implemented");
	}
	
	@Override
	public boolean tryLock() {		
		return lock.tryLock();
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit)
			throws InterruptedException {
		return lock.tryLock(time, unit);
	}

	@Override
	public void unlock() {
		lock.unlock();
	}


	@Override
	public void lock() {
		lock.lock();
	}

	public Id getDistributedObjectId() {
		return id;
	}
	
	public java.util.concurrent.locks.Lock getLockObject(){
		return lock;
	}
	
	public Id generateConditionObjectId(){
		return new Id(getDistributedObjectId()+Constant.ID_POSTFIX_CONDITION);
	}
}
